package com.veo.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.veo.entity.CommonResult;
import com.veo.entity.Payment;
import com.veo.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class OrderController {

    @Value("${service-url.nacos-user-service}")
    private String URL;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private PaymentService paymentService;


    @GetMapping("/consumer/fallback/{id}")
    //@SentinelResource(value = "fallback")//没有设置，报异常
    //@SentinelResource(value = "fallback",fallback = "handlerFallBack")//方法中有异常，就执行fallback指定的方法
    //@SentinelResource(value = "fallback",blockHandler = "blockHandler")//也就是说,blockHandler==只对sentienl定义的规则降级==
    @SentinelResource(value = "fallback",blockHandler = "blockHandler",fallback = "handlerFallBack",
    exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResult<Payment> fallback(@PathVariable("id")Long id) throws IllegalAccessException {

        CommonResult<Payment> result = restTemplate.getForObject(URL + "/payment/" + id, CommonResult.class, id);
        if(id == 4){
            throw new IllegalArgumentException("IllegalArgumentException 参数异常----------");
        }else if(result.getData() == null){
            throw new NullPointerException("NullPointerException 空指针异常------------");
        }
        return result;
    }

    public CommonResult handlerFallBack(@PathVariable("id")Long id,Throwable throwable){
        Payment payment = new Payment(id,null);
        return new CommonResult(44444,"兜底的异常处理方法"+throwable.getMessage(),payment);
    }

    public CommonResult blockHandler(@PathVariable("id")Long id, BlockException throwable){
        Payment payment = new Payment(id,null);
        return new CommonResult(66666,"blockHandler,没有该流水号"+throwable.getMessage(),payment);
    }

    @GetMapping("/consumer/payment/{id}")
    public CommonResult<Payment> commonResult1(@PathVariable("id")Long id){
        return paymentService.paymentCommonResult(id);
    }
}
